package cn.wolfcode.crm.realms;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm{

    @Autowired
    IEmployeeService employeeService;

    @Autowired
    IRoleService roleService;

    @Autowired
    IPermissionService permissionService;

    public String getName() {
        return "MyRealm";
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取令牌中的用户名
        Object principal = token.getPrincipal();
        //查询数据库是否存在该员工
        Employee employee = employeeService.getByUsername((String) principal);
        //如果存在就返回认证信息对象
        if(employee!=null){
            return new SimpleAuthenticationInfo(employee,employee.getPassword(),
                    ByteSource.Util.bytes(employee.getUsername()),getName());
        }
        //如果不存在就返回null
        return null;
    }

    /**
     * 授权
     * @param principals
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取当前登录的用户
        Employee employee = (Employee) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //判断是否管理员
        if(employee.isAdmin()){
            info.addRole("ADMIN");
            info.addStringPermission("*:*");
        }else {
            //获取用户拥有的角色的name集合
            info.addRoles(roleService.selectByEmployeeId(employee.getId()));
            //获取用户拥有的权限的resource集合
            info.addStringPermissions(permissionService.selectByEmployeeId(employee.getId()));
        }
        return info;
    }


}
